package cn.dubito.o2o.service.impl;

import cn.dubito.o2o.dao.ShopDao;
import cn.dubito.o2o.domian.dto.ShopExecution;
import cn.dubito.o2o.domian.enmus.ShopStateEnum;
import cn.dubito.o2o.domian.entity.Area;
import cn.dubito.o2o.domian.entity.Shop;
import cn.dubito.o2o.exception.ShopOperationException;
import cn.dubito.o2o.service.ShopService;
import cn.dubito.o2o.utils.ImageUtil;
import cn.dubito.o2o.utils.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

/**
 * @author liliang
 * @description:
 * @date 2018/4/18.
 */
@Service
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopDao shopDao;


    @Override
    public Shop getById(Long id) {
        return shopDao.queryById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ShopExecution addShop(Shop shop, MultipartFile shopImage) {
        // 判空操作
        if (shop == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        }
        // 初始化值
        shop.setEnableStatus(0);
        shop.setCreateTime(new Date());
        shop.setLastEditTime(new Date());
        // 添加店铺信息
        int eff = shopDao.insertShop(shop);
        if (eff <= 0) {
            throw new ShopOperationException("店铺创建失败");
        } else {
            if (shopImage != null) {
                addShopImage(shop, shopImage);
                // 更新图片地址
                eff = shopDao.updateShop(shop);
            }
            if (eff <= 0) {
                throw new ShopOperationException("更新图片地址失败");
            }
        }
        return new ShopExecution(ShopStateEnum.SUCCESS, shop);
    }

    private void addShopImage(Shop shop, MultipartFile shopImage) {
        // 获取 shop图片的相对路径
        String imagePath = PathUtil.getShopImagePath(shop.getId());
        String shopImagePath = ImageUtil.generateThumbnail(shopImage, imagePath);
        shop.setShopImg(shopImagePath);
    }

    @Override
    public ShopExecution modifyShop(Shop shop, InputStream shopInputStream) {
        if (shop == null || shop.getId() == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        } else {
            if (shopInputStream != null) {
                Shop shopDb = shopDao.queryById(shop.getId());
                if (shopDb != null && shopDb.getShopImg() != null) {
                    ImageUtil.deleteFileOrPath(shopDb.getShopImg());
                }

            }
        }
        return null;
    }
}
